package com.sari.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by HiZhengfu on 2014/8/19.
 * RequestContextUtils工具类
 */
public class RequestContextUtils {

    private static Logger logger = LoggerFactory.getLogger(RequestContextUtils.class);

    public static String httpRequest(String requestUrl) {
        StringBuffer buffer = new StringBuffer("");
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url
                    .openConnection();

            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

        } catch (Exception e) {
            logger.warn(Exceptions.getStackTraceAsString(e));
        }
        return buffer.toString();
    }

    /**
     * 获取requerst请求
     */
    public final static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 读取请求参数转换JSONObject对象
     *
     * @return JSONObject 对象
     */
    public final static JSONObject readJson() {
        return readJson(getRequest());
    }

    /**
     * 读取请求参数转换JSONObject对象
     *
     * @param request
     * @return JSONObject 对象
     */
    @SuppressWarnings("unchecked")
    public final static JSONObject readJson(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        if (request == null) return jsonObject;
        Map<String, String[]> map = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String key = entry.getKey().replaceAll("[\\W]", "");
            if (key.equals("_")) continue;
            if (entry.getValue().length > 1) {
                jsonObject.put(key, entry.getValue());
            } else {
                jsonObject.put(key, entry.getValue()[0]);
            }
        }
        return jsonObject;
    }


    /**
     * 获取网站上下文
     */
    public final static String getContextPath() {
        return getRequest().getContextPath();
    }
    
    /**
     * 获取网站绝对路径
     */
    public final static String getRealPath() {
        return getRequest().getSession().getServletContext().getRealPath("/");
    }
    
}
